<?php

namespace backend\controllers;

use common\models\category\Category;
use Yii;
use common\models\articles\Articles;
use common\models\articles\ArticlesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use zhongkefu\zhongkefu;
use zhongkefu\helpers\Utils;
use common\models\adminlog\AdminLog;
use common\models\Setting\Setting;

/**
 * ArticlesController implements the CRUD actions for Articles model.
 */
class ArticlesController extends BackendController
{

    public function actions()
    {
        return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imageUrlPrefix"  =>  Yii::$app->params['ueditor'],//图片访问路径前缀
                    "imagePathFormat" => '/upload/ariticle/ueditor/{yyyy}{mm}{dd}/{time}{rand:6}',//上传保存路径
                    "imageRoot" => Yii::getAlias("@webroot"),
                ],
            ]
        ];
    }


    /**
     * Lists all Articles models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticlesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionContentindex($id)
    {
        $searchModel = new ArticlesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $id);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Articles model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
		$model = $this->findModel($id);
		Adminlog::addlog(yii::$app->user->id, "查看文章 ".$model->title);
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Articles model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Articles();

        if ($model->load(Yii::$app->request->post())) {
             $model->img = UploadedFile::getInstance($model, 'img');
             $model->created_at = strtotime(Yii::$app->request->post()['Articles']['created_at']);
            if($model->img){
                $siteRoot = Yii::$app->params['articleimg'];
                $json = Utils::uploadfile($_FILES['Articles']['tmp_name']['img'],$_FILES['Articles']['name']['img'],$siteRoot);

                $model->img = $json;
            }
            $model->file = UploadedFile::getInstance($model, 'file');
             $model->created_at = strtotime(Yii::$app->request->post()['Articles']['created_at']);
            if($model->file){
                $siteRoot = Yii::$app->params['articleimg'];
                $json = Utils::uploadfile($_FILES['Articles']['tmp_name']['file'],$_FILES['Articles']['name']['file'],$siteRoot);

                $model->file = $json;
            }
            if(isset(Yii::$app->request->post()['tag'])){
                $model->optiontag = json_encode(Yii::$app->request->post()['tag']);
            }

                // 从百度编辑器提取图片
            if(Yii::$app->request->post()['Articles']['cover']){
                
                $pattern = '/src=\"([^\n]*)\"/iU';
                $conn = Yii::$app->request->post()['Articles']['cover'];

                preg_match_all($pattern, $conn, $cover);//匹配内容到arr数组
               // var_dump($cover[1][0]);die;
                $rs = explode("/", $cover[1][0]);
                $rs = array_slice($rs, -2);
                $rs = implode('/', $rs);
                $model->cover = $rs;
            }

             if($model->save()){
				$title = Yii::$app->request->post()['Articles']['title'];
				Adminlog::addlog(yii::$app->user->id, "添加文章 ".$title);
				
				$push = Yii::$app->request->post()['Articles']['push'];
				if($push){
					$aid = $model->attributes['id'];
					$this->baiduPush($aid); //百度推送
				}
                if(Yii::$app->request->post()['Articles']['cont'] == 1){
                    return $this->redirect(['create']);
                } else {
                    return $this->redirect(['contentindex', 'id' => Yii::$app->request->post()['Articles']['category_id']]);
                }
            }else{
                Yii::$app->session->setFlash('warning', Yii::t('app', '图片不能为空'));
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
         
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Articles model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) ) {

           $model->img = UploadedFile::getInstance($model, 'img');

            if($model->img){
                $siteRoot = Yii::$app->params['articleimg'];
                $json = Utils::uploadfile($_FILES['Articles']['tmp_name']['img'],$_FILES['Articles']['name']['img'],$siteRoot);
                $model->img = $json;
            }
            //若为更新图片，则为原数据库中图片名称
            if (!$model->img) {
                $new = $this->findModel($id);
                $model->img = $new->img;
            }
            $model->file = UploadedFile::getInstance($model, 'file');

            if($model->file){
                $siteRoot = Yii::$app->params['articlefile'];
                $json = Utils::uploadfile($_FILES['Articles']['tmp_name']['file'],$_FILES['Articles']['name']['file'],$siteRoot);
                $model->file = $json;
            }
            //若为更新文件，则为原数据库中文件名称
            if (!$model->file) {
                $new = $this->findModel($id);
                $model->file = $new->file;
            }
            if(isset(Yii::$app->request->post()['tag'])){
                $model->optiontag = json_encode(Yii::$app->request->post()['tag']);
            }
            if($model->save()){
				$title = Yii::$app->request->post()['Articles']['title'];
				Adminlog::addlog(yii::$app->user->id, "更新文章 ".$title);
				
				$push = Yii::$app->request->post()['Articles']['push'];
				if($push){
					$aid = $model->attributes['id'];
					$this->baiduPush($aid); //百度推送
				}
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->render('update', [
                    'model' => $model,
                ]);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    /**
     * 启用按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionStart()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $id){
                $model = Articles::findOne(['id' => $id]);
                Articles::updateAll(['status'=>Articles::STATUS_SUCCESS],['id' =>$model->id]);
            }
            return true;
        }
    }

    /**
     * 停用按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionStop()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $id){

                $model = Articles::findOne(['id' => $id]);
                Articles::updateAll(['status'=>Articles::STATUS_DELETED],['id' =>$model->id]);
            }
            return true;
        }
    }
    /**
     * 删除按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionAlldelete()
    {
		$artname='';
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
			foreach($ids as $val){
				$model = Articles::findOne(['id' => $val]);
				$artname .= $model->title.",";
			}
			$artname = substr($artname,0,-1);
            foreach($ids as $id){
                $this->findModel($id)->delete();
            }
			Adminlog::addlog(yii::$app->user->id, "批量删除文章 ".$artname);
            return true;
        }
    }
    /**
     * Deletes an existing Articles model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
		$model->delete();
		Adminlog::addlog(yii::$app->user->id, "删除文章 ".$model->title);
        return $this->redirect(['index']);
    }

     /**
     * 批量移动文章
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionMove()
    {
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            var_dump($ids);die;
            foreach($ids as $id){

                $model = Articles::findOne(['id' => $id]);
                Articles::updateAll(['category_id'=> 1],['id' =>$model->id]);
            }
            return true;
        }
    }

    /**
     * Finds the Articles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Articles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Articles::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	//百度文章实时推送
	protected function baiduPush($aid){
		
		$baiduinfo = setting::findBySql("select value from setting where code='tsurl' or code='tstoken'")->asArray()->all();
		$url = $baiduinfo[0]['value'];
		$token = $baiduinfo[1]['value'];
		$urls = array(
			'http://'.$url.'/articles/index/?id='.$aid,
		);
		
		$api = 'http://data.zz.baidu.com/urls?site='.$url.'&token='.$token;
		$ch = curl_init();
		$options =  array(
			CURLOPT_URL => $api,
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS => implode("\n", $urls),
			CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = json_decode(curl_exec($ch),true);
		if($result['success']){
			Articles::updateAll(['push_status'=>1],['id' =>$aid]);
		}
	}

    // 批量移动内容
    public function actionCatelist(){
        if(isset(zhongkefu::$app->request->post()["id"])){

            // $id = zhongkefu::$app->request->post()["id"];
            // $article = Articles::find()->select('id,category_id')->andWhere(['id'=>$id])->asArray()->one();
            $catelist = Category::find()->select('id, name')->asArray()->all();

            $arr = [
                'cate' => $catelist, // id,username 管理员id，管理员名，数组
                // 'mid'=>$id, // 要移动的id
                // 'uid'=>$article['category_id'] // 要移动的会员 原来的分类id
            ];

            return json_encode($arr);
        }
    }
    public function actionChangecate(){
        if((zhongkefu::$app->request->post()["id"]) != "") {

            $id = zhongkefu::$app->request->post()["articid"];
            $uid = zhongkefu::$app->request->post()["id"];
            $ids = explode(",", $id);
            Articles::updateAll(['category_id'=>$uid],['id' =>$ids]);
            return true;
        }
    }

}
